import React, { useState } from 'react';
import { useQuery, useAction, getAllQueries, provideAnswer } from 'wasp/client/operations';

const AdminPage = () => {
  const { data: queries, isLoading, error } = useQuery(getAllQueries);
  const provideAnswerFn = useAction(provideAnswer);
  const [currentAnswer, setCurrentAnswer] = useState({});

  if (isLoading) return 'Loading...';
  if (error) return 'Error: ' + error;

  const handleAnswerSubmit = (queryId) => {
    provideAnswerFn({ queryId, answerText: currentAnswer[queryId] || '' });
    setCurrentAnswer({ ...currentAnswer, [queryId]: '' });
  };

  return (
    <div className='p-4'>
      <h1 className='text-2xl font-bold mb-4'>Admin Page</h1>
      {queries.map((query) => (
        <div key={query.id} className='mb-4 p-4 bg-gray-100 rounded-lg'>
          <p className='font-semibold'>Question: {query.question}</p>
          <p className='mt-2'>Answer: {query.answer || 'No answer yet'}</p>
          <div className='mt-2'>
            <input
              type='text'
              value={currentAnswer[query.id] || ''}
              onChange={(e) => setCurrentAnswer({ ...currentAnswer, [query.id]: e.target.value })}
              placeholder='Type your answer here'
              className='px-3 py-2 border rounded w-full mb-2'
            />
            <button
              onClick={() => handleAnswerSubmit(query.id)}
              className='bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded'
            >
              Submit Answer
            </button>
          </div>
        </div>
      ))}
    </div>
  );
};

export default AdminPage;
